package yxy.game.pm2.command.friend;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.FriendMessage;
import yxy.game.pm2.module.chat.SingleChatBalckModule;
import yxy.game.pm2.module.friend.FriendModule;
import yxy.game.pm2.module.friend.NeedFriendList;

/**
 * 好友 拉黑
 *
 * @since 1.0
 */

/**
 * 好友 拉黑
 * 添加拉黑功能附加聊天屏蔽
 *
 * @since 2.0
 */
@MessageType(proto = Command.FriendBlack, classtype = FriendMessage.FriendBlackRequest.class)
public class CMD_FriendBlack extends Command<FriendMessage.FriendBlackRequest> {

	@Override
	public void execute(MessageSource messageSource, FriendMessage.FriendBlackRequest request) {
		String playerCode = messageSource.getTag();
		String blackCode = request.getPlayerCode();

		FriendMessage.FriendBlackResponse.Builder response = FriendMessage.FriendBlackResponse.newBuilder();

		if (blackCode.equals(playerCode)) {
			send(messageSource, response, Result.FriendCantAddSelf);
			return;
		}

		FriendModule friendModule = FriendModule.get(playerCode);
		FriendModule blackModule = FriendModule.get(blackCode);
		try {
			if (friendModule.tryLock() && blackModule.tryLock()) {
				friendModule.getBlack().add(blackCode);

				// 各种关系表中删除
				friendModule.getFriend().remove(blackCode);
				friendModule.getApply().remove(blackCode);

				blackModule.getFriend().remove(playerCode);
				blackModule.getApply().remove(playerCode);

				PlayerBean playerBean = PlayerBean.get(playerCode);
				ServerBean serverBean = ServerBean.get(playerBean.getServerId());
				AreaBean areaBean = AreaBean.get(serverBean.getAreaId());

				// 更新求好友列表
				NeedFriendList needFriendList = new NeedFriendList(areaBean.getGroupId());
				needFriendList.update(friendModule);
				needFriendList.update(blackModule);

				friendModule.set();
				blackModule.set();

                //添加到个人聊天黑名单
                SingleChatBalckModule singleChatBalckModule = SingleChatBalckModule.get(playerCode);
                singleChatBalckModule.setPlayerCodeToBlackSet(blackCode);

				send(messageSource, response, Result.Success);

			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			friendModule.unlock();
			blackModule.unlock();
		}
	}

	private void send(MessageSource messageSource, FriendMessage.FriendBlackResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}